<?php

namespace App\Admin\Controllers;

use App\Models\Test_config;
use DB;
use App\Models\Squad;
use App\Models\Notice;
use App\Models\Term;
use App\Models\Class_section_group;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use App\Admin\Extensions\TestReport;
use Illuminate\Http\Request;

class Test_configController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.test_config'));
            $content->description(trans('admin.list'));
            
            $content->body($this->grid()->render());
            Admin::script($this->test_js());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(trans('admin.test_config'));
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.test_config'));
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Test_config::class, function (Grid $grid) {
            //$grid->model()->where('create_user',Admin::user()->id);
            //超级管理员可看到所有数据
            if (Admin::user()->isAdministrator()) {
                
            }else{
                $grid->model()->where('create_user',Admin::user()->id);
            }
            $grid->id(trans('admin.ID'))->sortable();
            
            $grid->name(trans('admin.name'))->style('width:100px;word-break:break-all;');
            $grid->type('测试类型')->using([1=>'口试',2=>'笔试',3=>'阅读测试']);
            $grid->start_time(trans('admin.start_time'))->sortable();
            $grid->end_time(trans('admin.end_time'))->sortable();
            $grid->total_score(trans('admin.total_score'));
            $grid->squads('分配班级')->pluck('name')->label()->style('width:300px;word-break:break-all;');
            $grid->status(trans('admin.status'))->display(function($status){
                if($status == 1){
                    return '下线';
                }elseif($status == 0){
                    return '上线';
                }
            })->sortable();
            $grid->create_user('配置人')->display(function($create_user){
                return DB::table('admin_users')->where('id',$this->create_user)->value('username');
            });
            //禁用导出按钮
            $grid->disableExport();
            
            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });

            $grid->actions(function ($actions) {
                $actions->disableView();
                if($this->row->status == 0){
                    $actions->disableEdit();
                }
                $actions->disableDelete();
                $actions->append('<a class="glyphicon glyphicon-trash" onclick="test_delete('.$actions->getKey().')"></a>');
            });
        });
    }

    protected function test_js()
    {
        return <<<SCRIPT

        test_delete=function(id){
            //$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},async:false});
            
           /* var request = {id:id};
            $.post('test_config/delete',request,function(data){
                window.location.reload();
            })*/
            
                                        $.ajax({
                                method: 'post',
                                url: 'test_config/delete',
                                data: {
                                    _token:LA.token,
                                    id: id
                                },
                                success: function () {
                                    toastr.success('删除成功');
                                    parent.location.reload();
                                }
                            });
        }
SCRIPT;

    }

    public function delete(Request $request)
    {
        if(isset($request['id'])){
            Test_config::where('id',$request['id'])->delete();
            $test_assign = DB::table('test_assigns')->where('test_config_id',$request['id'])->get(['id']);
            $id = array();
            foreach($test_assign as $v){
                $id[] = $v->id;
            }
            Notice::whereIn('test_assign_id',$id)->update(['status'=>'5']);
            DB::table('test_assigns')->where('test_config_id',$request['id'])->delete();
        }
        return;
    }

    protected function my_grid()
    {
        $id = Admin::user()->id;
        return Admin::grid(Test_config::class, function (Grid $grid) use ($id) {
            $test_ids = DB::table('test_assigns as ta')->join('squads as s','ta.squad_id','=','s.id')
                ->where('s.class_teacher',$id)->select('ta.test_config_id')->get()->toArray();
            $test_config_ids = array();
            foreach($test_ids as $v){
                $test_config_ids[] = $v->test_config_id;
            }
            $grid->model()->whereIn('id',$test_config_ids);
            $grid->id(trans('admin.ID'))->sortable();

            $grid->name(trans('admin.name'))->style('width:100px;word-break:break-all;');
            
            $grid->start_time(trans('admin.start_time'))->sortable();
            $grid->end_time(trans('admin.end_time'))->sortable();
            $grid->total_score(trans('admin.total_score'));
            $grid->squads('分配班级')->pluck('name')->label()->style('width:300px;word-break:break-all;');

            //禁用导出按钮
            $grid->disableExport();

            $grid->tools(function ($tools) {
                //关闭批量删除
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->disableCreateButton();
            $grid->actions(function ($actions) {
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append(new TestReport($actions->getKey()));
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $term_start_date = Term::where('status','0')->value('start_date');
        $week =  ceil((time()-strtotime($term_start_date))/3600/24/7);
        return Admin::form(Test_config::class, function (Form $form) use($term_start_date,$week){
            
            $form->display('id', 'ID');
            for ($i=1; $i < 25; $i++) {
                $j = $i-1;
                $date_arr[$i] = '第'.$i.'周【'.date('Y/m/d',strtotime("$term_start_date +$j weeks")).'-'.date('Y/m/d',strtotime("$term_start_date +$i weeks -1 days")).'】';
            }
            
            $form->text('name',trans('admin.name'))->rules('required')->addElementLabelClass('must-input');
            $form->select('type','测试类型')->options([1=>'口试',2=>'笔试',3=>'阅读测试'])->default(1)->rules('required')->addElementLabelClass('must-input');
            $form->select('start_time','开始周')->options($date_arr)->default($week)->rules('required')->addElementLabelClass('must-input');
            $form->select('end_time','结束周')->options($date_arr)->default($week+2)->rules('required')->addElementLabelClass('must-input');
           
            $form->number('grace_days', trans('admin.grace_days'))->rules('required')->min(1)->max(30)->default(15)->addElementLabelClass('must-input')->help('在测试结束多少天后必须录入成绩！');
            $form->number('total_score', trans('admin.total_score'))->default(100)->rules('required')->addElementLabelClass('must-input');

            //根据当前登陆用户ID获取其所管的班段ID数组
            $section_ids = Class_section_group::where('pid','0')->whereRaw('find_in_set('.Admin::user()->id.',`charge`)')->pluck('id')->toArray();
            //在班级表找出section在$section_ids中的班级数组
            $tutor_squads1 = [];
            $tutor_squads2 = [];
            $tutor_squads3 = [];
            $tutor_squads = [];
            $tutor_squads1 = Squad::whereIn('section',$section_ids)->pluck('full_name','id')->toArray();
            //根据当前登陆用户ID获取其所管的分组ID数组
            $group_ids = Class_section_group::where('pid','>','0')->whereRaw('find_in_set('.Admin::user()->id.',`charge`)')->pluck('id')->toArray();
            //在班级表找出group在$group_ids中的班级数组
            $tutor_squads2 = Squad::whereIn('group',$group_ids)->pluck('full_name','id')->toArray();
            //根据当前登陆用户ID查找其所带的班级数组
            $tutor_squads3 = Squad::where('class_teacher',Admin::user()->id)->pluck('full_name','id')->toArray();
            //将3个数组合并去重得到当前用户所管的班级数组
            $tutor_squads = $tutor_squads1+$tutor_squads2+$tutor_squads3;
            $form->listbox('squads', '参与班级')->options($tutor_squads)->rules('required')->addElementLabelClass('must-input');
            $form->radio('status', trans('admin.status'))->options([0 => '上线', 1 => '下线'])->default(1)->addElementLabelClass('must-input');
            $form->hidden('create_user')->value(Admin::user()->id);
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
            $form->saving(function (Form $form) use($term_start_date){
               
                $start_week = $form->start_time-1;
                $end_week = $form->end_time;
                $form->start_time = date('Y-m-d H:i:s',strtotime("$term_start_date +$start_week week"));
                $form->end_time = date('Y-m-d H:i:s',strtotime("$term_start_date +$end_week week -1second"));
            });
            $form->saved(function (Form $form) {
                if($form->model()->status == 0){
                    $test_config_id= $form->model()->id;
                    $test_assign_ids = DB::table('test_assigns')->where('test_config_id',$test_config_id)->pluck('id')->toArray();
                    for ($i=0; $i <count($test_assign_ids) ; $i++) {
                        $test_assign_id = $test_assign_ids[$i];
                        $squad_id = DB::table('test_assigns')->where('id',$test_assign_id)->value('squad_id');
                        $tutor_id = Squad::find($squad_id)->class_teacher;
                        $squad_name = Squad::find($squad_id)->name;
                        $test_name = Test_config::find($test_config_id)->name;
                        $test_start_time = Test_config::find($test_config_id)->start_time;
                        $test_end_time = Test_config::find($test_config_id)->end_time;
                        $test_total_score = Test_config::find($test_config_id)->total_score;
                        $test_grace_days = Test_config::find($test_config_id)->grace_days;
                        $test_notice_end_time = date("Y-m-d H:i:s",strtotime("+".$test_grace_days."days",strtotime($test_end_time)));
                        if ($test_notice_end_time<date('Y-m-d H:i:s')) {
                            $status = '3';
                        }
                        else{
                            $status = '1';
                        }
                        $data[] = [
                            'notice_type' =>'2',
                            'test_assign_id' =>$test_assign_id,
                            'event' =>'测试/'.$squad_name.'/'.$test_name.'('.date('Y-m-d',strtotime($test_start_time)).'~：'.date('Y-m-d',strtotime($test_end_time)).")",
                            'starttime' =>$test_start_time,
                            'grace_days'=>$test_grace_days,
                            'endtime' =>$test_notice_end_time,
                            'status'=>$status,
                            'squad_id' => $squad_id,
                            'tutor_id' => $tutor_id
                        ];
                        // dd($data);
                    }
                    $res = Notice::insert($data);
                }
                //dd($test_assign_ids);
            });
        });
    }

    public function my_test()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.test_config'));
            $content->description(trans('admin.list'));

            $content->body($this->my_grid()->render());
        });
    }
}
